package besta.moon.engine.store;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.sql.SQLException;

import besta.moon.MoonException;
import besta.moon.MoonConnection;
import besta.moon.MoonCode;
import besta.moon.engine.Database;
import besta.moon.engine.TransactionStep;

public class CreateFile extends TransactionStep {

    private final File file;
    private final MoonConnection con;
    private final Database database;

    public CreateFile(File file, FileChannel raFile, MoonConnection con,
            Database database) {
        super(raFile);
        this.file = file;
        this.con = con;
        this.database = database;
    }

    @Override
    public long commit() {
        raFile = null;
        return -1;
    }

    @Override
    public void rollback() throws SQLException {
        FileChannel currentRaFile = raFile;
        if (raFile == null) {
            return;
        }
        raFile = null;
        try {
            currentRaFile.close();
        } catch (IOException ex) {
       
        }
        con.rollbackFile(currentRaFile);
        if (!file.delete()) {
            file.deleteOnExit();
            throw MoonException.create(MoonCode.FILE_CANT_DELETE,
                    file.getPath());
        }

        String name = file.getName();
        name = name.substring(0, name.lastIndexOf('.'));
        database.removeTableView(name);
    }

}
